﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

namespace NJL.WebUsers
{
    public partial class Register : BasePageVisitor
    {
        BLL.NJL_USER bllUser = new BLL.NJL_USER();
        Model.NJL_USER modelUser = new Model.NJL_USER();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (UserId != "")
            {
                Response.Redirect("/");
            }
            if (IsPostBack)
            {
                if (!string.IsNullOrEmpty(txtPwdEmail.Text.Trim()))
                {
                    txtPwdEmail.Attributes["value"] = txtPwdEmail.Text.Trim();
                }
                if (!string.IsNullOrEmpty(txtconfirmPwdEmail.Text.Trim()))
                {
                    txtconfirmPwdEmail.Attributes["value"] = txtconfirmPwdEmail.Text.Trim();
                }
            }
            if (!IsPostBack)
            {
                LoadPageSEO();
            }
        }

        /// <summary>
        /// 加载页面SEO
        /// </summary>
        private void LoadPageSEO()
        {
            //Page.Title = "用户注册-" + WEBSITE_SYS_BASE.WEBSITE_NAME;

            //HtmlMeta myMeta = new HtmlMeta();
            //myMeta.Name = "Keywords";
            //myMeta.Content = WEBSITE_SYS_BASE.WEBSITE_KEYWORDS;
            //this.Header.Controls.Add(myMeta);

            //HtmlMeta myMeta1 = new HtmlMeta();
            //myMeta1.Name = "Description";
            //myMeta1.Content = WEBSITE_SYS_BASE.WEBSITE_DESCRIPTION;
            //this.Header.Controls.Add(myMeta1);
        }
        protected void btnSubmitEmail_Click(object sender, EventArgs e)
        {
            if (Session["CheckCodeEmail"] != null)
            {
                if (Session["CheckCodeEmail"].ToString().ToLower() != txtCheckCodeEmail.Text.Trim().ToLower())
                {
                    Royalsoft.Common.MessageBox.Show(this, "请输入正确的验证码");
                    txtCheckCodeEmail.Text = string.Empty;
                    return;
                }
                string email = txtEmail.Text.Trim();
                string userName = txtUserNameEmail.Text.Trim();
                string password = txtPwdEmail.Text.Trim();
                string passwordMd5 = hidPasswordCellEmail.Value;
                if (bllUser.GetEmailPhoneByEmail(email))
                {
                    Royalsoft.Common.MessageBox.Show(this, "电子邮件地址已经注册");
                    return;
                }
                modelUser.ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(100, 999).ToString();
                modelUser.USER_NAME = userName;
                modelUser.USER_PASSWORD = password;
                modelUser.USER_PASSWORD_MD5 = passwordMd5;
                modelUser.EMAIL = email;
                modelUser.CREATE_DATE_TIME = DateTime.Now;
                modelUser.NJL_SYS_BASE_ID = WEBSITE_CODE;
                modelUser.TYPE_CODE = "-1";      //完成第一步注册,未选择用户类型//-1:注册成功，未激活/0:激活但是为选择用户状态 
                modelUser.AUTHENTICATION_CODE_EMAIL = System.Guid.NewGuid().ToString();
                modelUser.INTEGRAL = 0;
                if (bllUser.Add(modelUser))
                {
                    Session.Add("userid", modelUser.ID);
                    Session.Add("username", modelUser.USER_NAME);
                    Session.Add("usertype", "-1");

                    try
                    {
                        RegisterMail(email, email, "", modelUser.AUTHENTICATION_CODE_EMAIL, "email", modelUser.USER_PASSWORD, modelUser.CREATE_DATE_TIME.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                        Royalsoft.Common.MessageBox.ShowAndRedirect(this, "账户激活邮件已发送到您的注册邮箱中，请查收！", "RegisterActive.aspx");
                    }
                    catch
                    {
                        Royalsoft.Common.MessageBox.ShowAndRedirect(this, "邮件服务器连接失败,请重新获取激活邮件！", "RegisterActive.aspx");
                    }

                }
            }
            else
            {
                Royalsoft.Common.MessageBox.ShowAndRedirect(this, "连接系统超时", "Register.aspx");
            }
        }

        private System.Net.Mail.MailMessage RegisterMail(string txtMailTo, string Email, string QQ, string Code, string Type, string LoginPassword, string RegisterDateTime)
        {
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();

            System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["MailAddressFrom"], txtMailTo.Trim());
            mm.Subject = System.Configuration.ConfigurationManager.AppSettings["WebSiteName"] + "-账户验证激活邮件";
            mm.Body = GetEmailBody(txtMailTo, Email, QQ, Code, Type, LoginPassword, RegisterDateTime);
            mm.IsBodyHtml = true;
            mm.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
            smtp.Send(mm);
            return mm;
        }

        private static string GetEmailBody(string txtMailTo, string Email, string QQ, string Code, string Type, string LoginPassword, string RegisterDateTime)
        {
            string strRegisterOkUrl = "http://" + System.Configuration.ConfigurationManager.AppSettings["WebSiteDomain"] + "/RegisterActive.aspx?option=active&type=" + Type + "&email=" + Email + "&qq=" + QQ + "&code=" + Code;
            string strWebsiteDomain = "http://" + System.Configuration.ConfigurationManager.AppSettings["WebSiteDomain"];
            string strWebsiteName = System.Configuration.ConfigurationManager.AppSettings["WebSiteName"];
            string strRegisterUserName = txtMailTo;
            string strRegisterPassword = LoginPassword;
            string strRegisterDateTime = RegisterDateTime;


            Encoding code = Encoding.GetEncoding("GB2312");
            // 读取模板文件 
            string temp = HttpContext.Current.Server.MapPath("~/EmailTemplate/RegisterOK.html");
            StreamReader sr = null;
            //StreamWriter sw = null;
            string str = "";
            try
            {
                sr = new StreamReader(temp, code);
                str = sr.ReadToEnd(); // 读取文件 
            }
            catch (Exception exp)
            {
                HttpContext.Current.Response.Write(exp.Message);
                HttpContext.Current.Response.End();
                sr.Close();
            }

            // 替换内容 
            // 这时,模板文件已经读入到名称为str的变量中了 
            str = str.Replace("{$WebSiteDomain$}", strWebsiteDomain); //模板页中的ShowArticle 
            str = str.Replace("{$WebSiteName$}", strWebsiteName);
            str = str.Replace("{$RegisterOkUserName$}", strRegisterUserName);
            str = str.Replace("{$RegisterOkPassword$}", strRegisterPassword);
            str = str.Replace("{$RegisterActiveUrl$}", strRegisterOkUrl);
            str = str.Replace("{$RegisterOkDateTime$}", strRegisterDateTime);

            return str;
        }
    }
}